import { apiRequest, showNotification } from './utils.js';

// 分类管理模块
export class CategoryModule {
  constructor() {
    this.categories = [];
    this.newCategory = {
      id: null,
      name: '',
      description: ''
    };
    this.editingCategory = null;
  }

  // 加载分类列表
  async loadCategories() {
    try {
      this.categories = await apiRequest('/api/categories');
      return this.categories;
    } catch (error) {
      console.error('加载分类数据失败:', error);
      throw error;
    }
  }

  // 创建或更新分类
  async saveCategory(categoryData) {
    try {
      let result;
      if (categoryData.id) {
        // 更新分类
        result = await apiRequest(`/api/categories/${categoryData.id}`, {
          method: 'PUT',
          body: JSON.stringify(categoryData)
        });
        // 更新本地列表
        const index = this.categories.findIndex(c => c.id === result.id);
        if (index !== -1) {
          this.categories[index] = result;
        }
        showNotification('分类更新成功', 'success');
      } else {
        // 创建新分类
        result = await apiRequest('/api/categories', {
          method: 'POST',
          body: JSON.stringify(categoryData)
        });
        this.categories.push(result);
        showNotification('分类创建成功', 'success');
      }
      return result;
    } catch (error) {
      console.error('保存分类失败:', error);
      throw error;
    }
  }

  // 删除分类
  async deleteCategory(categoryId) {
    try {
      await apiRequest(`/api/categories/${categoryId}`, {
        method: 'DELETE'
      });
      // 从本地列表中移除
      this.categories = this.categories.filter(c => c.id !== categoryId);
      showNotification('分类删除成功', 'success');
      return true;
    } catch (error) {
      console.error('删除分类失败:', error);
      throw error;
    }
  }

  // 设置编辑分类
  setEditingCategory(category) {
    this.editingCategory = category;
    if (category) {
      this.newCategory = { ...category };
    } else {
      this.newCategory = {
        id: null,
        name: '',
        description: ''
      };
    }
  }
}